<?php

namespace control;

class fileUploadClass extends adIndexClass
{
    private const title = '文件上传类';
    private const page  = 'fileUpload';


    public static function singleFrameImgUpload($data){
        $li = "";
        foreach ($data['array'] as $num => $array) {
            //编辑表单
            $click = '';
            if (!empty($array['id'])) {
                $click = "<div class='clickIco' title='上传'><img  src='" . root . "img/control/clickEdit.svg?v=".version."' onClick=\"clickUpload('{$array['type']}')\" class='edit-ico'></div>";
                if (!empty($array['fileId'])) {
                    $click = "<div class='clickIco' title='删除'><img  src='" . root . "img/control/singleDel.svg?v=".version."' onClick=\"delSingleIco('{$array['fileId']}','{$data['power']}')\" class='edit-ico'></div>";
                }
            }
            //点击显示大图功能
            if (empty($array['url'])) {
                $img = "<img class='smallImg imgHover' data-type='{$array['type']}' src='" . root . "img/images/emptyImg.jpg'>";
            } else {
                if (strstr($array['url'], "http") !== false) {
                    $r = "";
                } else {
                    $r = root;
                }
                $img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img data-type='{$array['type']}' class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
            }
            //打印本图像框
            $li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
			</li>
			";
        }
        $data['postUrl'] = $data['postUrl']??root.'control/adIndex.html?cla='.self::page."&fun=uploadSingleFrameImg";
        $version = version;
        return <<<efo
		<div class='imgSingle'>
			<ul>{$li}</ul>
			<div class='clear'></div>
		</div>
        <div class='hidden'><input name="singleFrameImgType" type="hidden"><input name='imgFile' accept="image/*" id='imgFile' type='file' onchange="uploadImgFile('{$data['formName']}','{$data['postUrl']}','{$data['power']}')"></div>
		<script>
		//点击上传图片
        function clickUpload(type){
            $('[name=singleFrameImgType]').val(type);
            $('#imgFile').click();
        }
        //上传图片
        function uploadImgFile(formName,url,power){
            let form = $("form[name='"+formName+"']")[0];
            let type = $('[name=singleFrameImgType]').val();
              $('[name=singleFrameImgType]').val('');
            let formData = new FormData(form);
            formData.append('power',power);
            formData.append('singleFrameImgType',type);
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='imgFile']").val('');
                    if (result.warn === 2) {
                      
                        let img = $("[data-type='"+type+"']");
                        img.attr('src',result.data.src);
                        img.after(result.data.html);
                        img.closest('li').find(".edit-ico").attr('src',root+'img/control/singleDel.svg?v=$version');
                        img.closest('li').find(".edit-ico").attr('onclick',"delSingleIco('"+result.data.id+"','"+power+"')")
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    warn("上传失败");
                }
            });
        }
 function delSingleIco(id,power){
  $.post(root+'control/adIndex.html?cla=fileUpload&fun=delSingleFrameImg',{id:id,power:power},function(res) {
        if (res.warn ==2){
            $("[name='iconId[]'][value='"+id+"']").remove();
            $("[data-type='"+res.data.type+"']").attr('src',root+'img/images/emptyImg.jpg')
             $("[data-type='"+res.data.type+"']").closest('li').find(".edit-ico").attr('src',root+'img/control/clickEdit.svg?v=$version');
             $("[data-type='"+res.data.type+"']").closest('li').find(".edit-ico").attr('onclick',"clickUpload('"+res.data.type+"')")
        }else{
            msg(res.warn,'error')
        }
   },'json')
 }
        </script>
efo;
    }

    /**
     * 上传单个图片
     * @return bool|string
     */
    function uploadSingleFrameImg()
    {
        $type = $this->post('singleFrameImgType');
        $power = $this->post('power');
        $info = query('file', " id = '{$this->post('id')}'");
        if (empty($power) || !$this->power($power, 'edit')) {
            $json['warn'] = "您还没有编辑的权限";
        } else {
            return $this->saveIco($power, $info['id'], $type, $_FILES);
        }
        return json_encode($json, 320);
    }

    /**
     * 删除单个图片
     * @return false|string
     */
    public function delSingleFrameImg()
    {
        $id = $this->post('id');
        $power = $this->post('power');
        if (empty($power) || !$this->power($power, 'edit')) {
            $json['warn'] = "您还没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = '未找到要删除的文件ID';
        } else {
            $file = query('file', "id = '$id'");
            $json['warn'] = delete(array('table' => 'file', 'where' => "id = '$id'"));
            if ($json['warn'] == '删除成功') {
                fileDelete($file['src']);
                $json['data']['type'] = $file['target'];
                $text=str_replace(['{{staffName}}','{{fileName}}','{{type}}','{{id}}'],[$this->control['name'],$file['name'],$file['target'],$id],L('staffProfiles.talentPool.delFile'));
                $this->logText(["type" => $power, "text" => $text]);
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    public function saveIco($page, $id, $type, $fileArr): bool|string
    {
        $result = $this->saveFile($fileArr['imgFile'], $page, explode(',', para('fileFormat')));
        if (!$result['code']) {
            $json['warn'] = $result['warn'];
        } else {
            $file = query('file', "id = '$id'");
            $field = [
                'name' => $result['fileName'],
                'format' => $result['suffix'],
                'size' => $result['size'],
                'src' => $result['src']
            ];
            if (empty($file['id'])) {
                $suiji = suiji();
                $field = array_merge(
                    $field,
                    [
                        'id' => $suiji,
                        'stid' => self::$stid,
                        'target' => $type,
                    ]
                );
                $json['warn'] = static::insert(array(
                    'table' => 'file',
                    'field' =>$field
                ));
            } else {
                $json['warn'] = static::update(array(
                    'table' => 'file',
                    'field' => $field,
                    'where' => "id = '$file[id]'"
                ));
                $suiji = $file['id'];
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{fileName}}','{{type}}','{{id}}'],[$this->control['name'],$result['fileName'],$type,$suiji],L('staffProfiles.talentPool.saveIco'));
                $this->logText(["type" => $page, "text" => $text]);
            }
            //添加日志
            if (in_array($json['warn'], ['新增成功', '更新成功'])) {
                fileDelete($file['src']);//删除之前的图片
                $json['warn'] = 2;
                $json['data']['src'] = root . $result['src'];
                $json['data']['id'] = $suiji;
                $json['data']['html'] = hidden(['name'=>'iconId[]','value'=>$suiji]);
            }
        }
        return json_encode($json, 320);
    }


    public static function icon($data)
    {
        //参数准备
        $html = "";
        $para = array(
            "download" => "下载",
            "preview"  => "文档预览",
            "img"      => "图片预览"
        );
        //循环
        foreach ($data as $name => $array) {
            //标题
            $title = (empty($array['title'])) ? ($para[$name] ?? null) : $array['title'];
            if (empty($array)) {
                continue;
            }
            if ($name == "download") {
                if (!empty($array['href'])) {
                    $html .= "\n<a target='_blank' href='" . root . $array['href'] . "' download='" . $array['name'] . "' title='" . $title . "'><img  alt='' src='" . root . "img/control/download.svg' class='listIco'></a>";
                }
            } elseif ($name == "preview") {
                if (!empty($array['href'])) {
                    $url  = self::wps($array);
                    $html .= "\n<a target='_blank' href='" . $url . "' title='" . $title . "'><img alt='' src='" . root . "img/control/preview.svg' class='listIco'></a>";
                }
            } elseif ($name == "img") {
                if (!empty($array['href'])) {
                    $html .= "\n<a target='_blank' href='" . root . $array['href'] . "?time=" . time() . "'><img alt='' src='" . root . "img/control/img.svg' title='" . $title . "' class='listIco'></a>";
                }
            } elseif (array_key_exists($name, $para)) {
                $html .= "\n<img onclick=\"" . $array['click'] . "\" title='" . $title . "' src='" . root . "img/control/" . $name . ".svg' class='listIco'>";
            }
        }
        //返回
        return $html;
    }

    /**
     * @param $id
     * @param string $type
     * @return string
     */
    public static function showSingFile($id, $type = ''): string
    {
        $where    = $type ? " and target = '$type'" : '';
        $file     = query('file', "targetId = '$id' and targetId !='' " . $where);
        $dominate = array(
            "download" => array("name" => $file['name'], "href" => $file['src']),
        );
        if (in_array($file['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
            $dominate['preview'] = array("format" => $file['format'], "name" => $file['name'], "href" => $file['src']);
        } elseif (in_array($file['format'], array("png", "gif", "jpg"))) {
            $dominate['img'] = array("title" => "在线预览", "href" => $file['src']);
        }
        return "<span class='del-row-button'>{$file['name']}</span>" . self::icon($dominate);

    }

    /**
     * 单个文件上传组件
     */
    public static function singleUpload($formName, $power, $id, $type): string
    {
        $where = $type ? " and target = '$type'" : '';
        /*******附件****************/
        $file           = query('file', "targetId = '$id' and targetId !='' " . $where);
        $fileCollection = $file['name'];
        if (empty($file['id'])) {
            //显示上传按钮
            $src    = root . 'img/control/upload.svg';
            $direct = 'add';
        } else {
            //显示删除按钮
            $src    = root . 'img/control/delete.svg';
            $direct = 'delete';
        }
        return "<div><span id='singFileName' class='del-row-button'>{$fileCollection}</span> <img data-type='$direct' onclick=\"button_method(this,'$power')\"  id='upload-ico' src='$src' style='width: 22px;height: 22px;margin-left: 5px;cursor: pointer' alt=''/>" . hidden(array('name' => 'fileId', 'value' => $file['id'])) . hidden(array('name' => 'targetId', 'value' => $id)) . "</div>
                <div class='hidden'><input name='fileType' value='{$type}'><input name='uploadFile' id='uploadFile' type='file' onchange=\"uploadSingleFile('$formName',root+'control/adIndex.html?cla=fileUpload&fun=uploadSingleFile&power={$power}')\"></div>";
    }

    /**
     * 单个文件保存
     */
    public function uploadSingleFile(): bool|string
    {
        $file  = $_FILES['uploadFile'] ?? [];
        $power = $this->get('power');
        $type  = $this->post('fileType');
        $id    = $this->post('targetId');
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($type)) {
            $json['warn'] = '未找到上传的类型';
        } else {
            $result = $this->saveFile($file, $power, explode(',', para('fileFormat')));
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                $file = query('file', "target = '$type' and targetId = '$id'");
                if (empty($file['id'])) {
                    $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' => $type, 'name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src']);
                    $warn  = static::insert(array('table' => 'file', 'field' => $field));
                } else {
                    $field       = array('name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src']);
                    $warn        = static::update(array('table' => 'file', 'where' => "id = '$file[id]'", 'field' => $field));
                    $field['id'] = $file['id'];
                }
                if (in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn']         = 2;
                    $json['data']['id']   = $field['id'];
                    $json['data']['src']  = root . $field['src'];
                    $json['data']['name'] = $field['name'];
                } else {
                    $json['warn'] = '上传失败';
                }
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 上传图片
     *
     * @param        $id
     * @param string $type
     * @param string $power
     * @param string $formName
     * @return string
     */
    public static function addImgComponent($id, string $type, string $power, string $formName): string
    {
        $root           = root;
        $fileCollection = '';
        $result         = find(array('table' => "file", 'where' => "targetId !='' and targetId = '{$id}' and target='{$type}' order by time asc"));
        foreach ($result['array'] as $array) {
            $fileCollection .= <<<efo
 <li><img class="li-ico" alt="" src="{$root}{$array['src']}"><a onclick="del_img('{$array['id']}','{$power}',this)" href='javascript:void(0)'><div><span class='u-icon-delete'><i></i></span></div></a></li>
efo;
        }
        return <<<eof
 <div class='img-list'>
 <ul class="img-ul">{$fileCollection}<li id="add-img-btn" ><div title="上传图片"  onclick="$('#uploadImg').click();"  class="add-img-btn">+</div></li></ul>
                     <div class='hidden'><input name='imgType' value='{$type}'><input name='uploadImg' id='uploadImg' accept="image/*" type='file' onchange="uploadAttachFile('{$formName}',root+'control/adIndex.html?cla=fileUpload&fun=uploadImg&power={$power}','add-img-btn')"></div>
</div>
<script>
function del_img(id,power,e){
     let url = root + "control/adIndex.html?cla=fileUpload&fun=delFile";
    $.post(url, {
        id: id,
        power: power
    }, function (res) {
        if (res.warn === 2) {
            $(e).parent().remove();
        } else {
            warn(res.warn);
        }
    }, 'json')
}
</script>
<style>

</style>
eof;
    }

    /**
     * 文件添加组件
     *
     * @param $id       string 对象ID
     * @param $type     string 对象类型（例如 证件管理、稽核记录等）
     * @param $power    string 权限
     * @param $formName string 表单名称
     * @return string
     */
    public static function addFileComponent(string $id, string $type, string $power, string $formName): string
    {
        /*******附件****************/
        $fileCollection = '';
        $result         = find(array('table' => "file", 'where' => "targetId !='' and targetId = '{$id}' and target='{$type}' order by time asc"));
        foreach ($result['array'] as $array) {
            $size           = self::formatSize($array['size']);
            $view           = self::view($array['src'], true, $array['name']);
            $title          = $array['name'];
            $fileCollection .= "
                                    <div class='file_block_bg'>
                                        <img  src='" . root . "img/control/annex.svg'>
                                        <div class='file_block_right'>
                                            <div class='file_block_right_text' title='$title'>$title</div>
                                            <span class='title-color'>$size</span>
                                            $view
                                            <span class='del-row-button' onclick=\"delFile('{$array['id']}','{$power}',this)\">删除</span>
                                        </div>
                                    </div>
        ";
        }
        $blockId = self::getId();
        $butId = self::getId();
        $inputId = self::getId();
        return "
            <div class='file_block_bg_parent' id='{$blockId}'>
                {$fileCollection}
                <div id='{$butId}' onclick=\"$('[name={$formName}] #{$inputId}').click();\" title='点击上传文件或粘贴复制的文件到框中' class='file_block_add_btn'>+</div>
                ".(new self())->dragUploadHtml($type, root."control/adIndex.html?cla=fileUpload&fun=uploadFileChunk", $blockId, $power, $butId)."
            </div>
            <div class='hidden'>
                <input name='fileType' value='{$type}'>
                <input name='uploadFile' id='{$inputId}' type='file' multiple onchange=\"uploadAttachFileChunk(this, '{$power}', '{$type}',root+'control/adIndex.html?cla=fileUpload&fun=uploadFileChunk','{$butId}','{$blockId}')\">
            </div>
        ";
    }

    /**
     * 上传附件
     */
    public function uploadFile()
    {
        $file = $_FILES['uploadFile'] ?? [];
        $power = $this->get('power');
        $type = $this->post('fileType');
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($type)) {
            $json['warn'] = '未找到上传的类型';
        } else {
            $result = $this->saveFile($file, $power, explode(',', para('fileFormat')));
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' => $type, 'name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src'], 'updateTime' => $this->time, 'time' => $this->time);
                $warn = insert(array('table' => 'file', 'field' => $field));
                if ($warn == '新增成功') {
                    $json['warn'] = 2;
                    $json['data']['id'] = $field['id'];
                    $json['data']['src'] = root . $field['src'];
                    $size = self::formatSize($field['size']);
                    $title = $field['name']."($size)";
                    $json['data']['html'] = "<div class='file_block_bg'>
                                                <img  src='" . root . "img/control/annex.svg'><input name='fileId[]' type='hidden' value='{$field['id']}' />
                                                <div class='file_block_right'><div class='file_block_right_text' title='$title'>$title</div><div class='del-row-button'  onclick=\"delFile('{$field['id']}','{$power}',this)\">删除</div></div>
                                        </div>";
                } else {
                    $json['warn'] = '上传失败';
                }
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 上传附件
     */
    public function uploadFileChunk()
    {
        $shareObj = new shareClass();
        $file = $_FILES['file'] ?? [];
        $info = json_decode($_POST['info'],true);
        $state = 0;
        $json = [];
        $limitType = explode(',', para('fileFormat'));
        $suffix   = self::getExtension($this->post('name'));
        $upload_progress = query("upload_progress"," id = '".$info['id']."' ");
        if (empty($info)) {
            $json['warn'] = '未找到上传的数据';
        } elseif (empty($upload_progress['id'])) {
            $json['warn'] = 1;
        } elseif (!empty($limitType) && !in_array($suffix, $limitType)) {
            $json['warn'] = '你上传的文件不在上传类型范围中';
        } elseif (!$this->power($info['power'], 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } else {
            $result = $shareObj->saveFileTemp($file, $info['id'].'_'.$this->post('chunk'));
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                //判断分片是否全部上传完成
                $uploadStatus = true;
                for ($i = 1; $i <= $this->post('chunks'); $i++) {
                    if (!file_exists(serverRoot . 'file/temp/' . $info['id'] . "_" . $i)) {
                        $uploadStatus = false;
                        break;
                    }
                }
                if (!$uploadStatus) {
                    $progress = round($this->post('chunk') / $this->post('chunks') * 100, 2);
                }else {
                    //合并分片
                    $url = 'file/'.$info['power'].'/' . date("Ym");
                    $this->_mkdir($url);
                    $fileName = suiji().'.'.$suffix;
                    $fp = fopen(serverRoot.$url .'/'. $fileName, "w");
                    for ($i = 1; $i <= $this->post('chunks'); $i++) {
                        $chunkName = serverRoot . 'file/temp/' . $info['id'] . "_" . $i;
                        $chunkData = file_get_contents($chunkName);
                        fwrite($fp, $chunkData);
                        @unlink($chunkName); //删除分片文件
                    }
                    fclose($fp);
                    $id  = self::getNo();
                    $field = array(
                        'id' => $id,
                        'stid' => $this->control['stid'],
                        'target' => $upload_progress['target'],
                        'name' => $this->post('name'),
                        'format' => $suffix,
                        'size' => $this->post('size'),
                        'src' => $url .'/'. $fileName,
                        'updateTime' => $this->time,
                        'time' => $this->time
                    );
                    $json['warn']  = insert(array('table' => 'file', 'field' => $field));
                    if ($json['warn'] == "新增成功") {
                        $state = 1;
                        $progress = 100;
                        $json['id']   = $id;
                        $json['src']  = root . $field['src'];
                        $size                 = self::formatSize($field['size']);
                        $title                = $field['name'];
                        $view           = self::view($field['src'], true, $field['name']);
                        $json['html'] = "<div class='file_block_bg' progress-id='{$info['id']}'>
                                                <img  src='" . root . "img/control/annex.svg'><input name='fileId[]' type='hidden' value='{$field['id']}' />
                                                <div class='file_block_right'>
                                                    <div class='file_block_right_text' title='$title'>$title</div>
                                                    <span class='title-color'>$size</span>
                                                    ".$view."
                                                    <span class='del-row-button'  onclick=\"delFile('{$field['id']}','{$info['power']}',this)\">删除</span>
                                                </div>
                                        </div>";
                    }else{
                        goto resp;
                    }
                }
                $json['warn'] = static::update([
                    "table" => 'upload_progress',
                    "field" => ['chunk' => $this->post('chunk'), 'state' => $state, 'updateTime' => $this->time],
                    "where" => " id = '" . $info['id'] . "' "
                ]);
                if($json['warn'] == '更新成功') {
                    $json['warn'] = 2;
                    $json['state'] = $state;
                    $json['progress'] = $progress;
                    if($state == 1)$_SESSION['warn'] = '上传成功';
                }
                goto resp;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * Desc : 拖拽上传
     * User : you name
     * Date : 2024-02-21 09:38
     * @param $target
     * @param $url
     * @param $node
     * @param $power
     * @param $htmlId
     * @return string
     */
    public function dragUploadHtml($target, $url, $node, $power, $htmlId)
    {
        return "
    <div id='windowMaskViewAnnex' class='maskViewAnnex'></div>
    <div id='maskViewContentAnnex' class='viewContentAnnex'>
        <div class='content-div'>
            <div class='upload-tips'>						
                <div class='cloud-moveup'>
                    <i class='moveTopLoop icon-circle-arrow-up'></i>
                </div>						
                <div class='msg'>松开即可上传!</div>
            </div>
        </div>
    </div>
    <script>
        var target = '{$target}'
        var url = '{$url}'
        var node = '{$node}'
        var power = '{$power}'
        var htmlId = '{$htmlId}'
        $(document).ready(function(){
            let elemetnNode=''//最后一次节点
            //要想实现拖拽，首页需要阻止浏览器默认行为，一个四个事件。
            $('#'+node).on({
                dragleave:function(e){		//拖离
                    e.preventDefault();     //移除原有浏览器监听效果
                    if(elemetnNode===e.target)
                    $('.maskViewAnnex,.viewContentAnnex').removeClass('over');
                },
                drop:function(e){			//拖后放
                    e.preventDefault();     //移除原有浏览器监听效果
                    
                },
                dragenter:function(e){		//拖进
                    elemetnNode=e.target;
                    e.preventDefault();     //移除原有浏览器监听效果
                    $('.maskViewAnnex,.viewContentAnnex').addClass('over');
                },
                dragover:function(e){		//拖来拖去
                    e.preventDefault();     //移除原有浏览器监听效果
                    $('.maskViewAnnex,.viewContentAnnex').addClass('over');
                }
            });
            
            //================上传的实现
            var box = document.getElementById(node); //获得到框体
            var newHandle = function(e){
                e.preventDefault(); //取消默认浏览器拖拽效果
                e.stopPropagation()
                var fileList = e.dataTransfer.files; //获取文件对象
                //fileList.length 用来获取文件的长度（其实是获得文件数量）
                
                //检测是否是拖拽文件到页面的操作
                if(fileList.length === 0){
                    $('.maskViewAnnex,.viewContentAnnex').removeClass('over');
                    return;
                }
                var arr = [];
                const chunkSize = 5 * 1024 * 1024;
                $.each(fileList,function(n,file){
                    var error = ''
                    if($('#'+node).find(\"[title='\"+file.name+\"']\").length > 0){
                        error = '上传失败，已存在此附件'
                    }
                    var value = {
                        'code':  CryptoJS.MD5(file.name + file.size + file.lastModified).toString(),
                        'target':  target,
                        'name':  file.name,
                        'size':  file.size,
                        'target_id':  '',
                        'chunks':  Math.ceil(file.size / chunkSize),
                        'power':  power,
                        'error':  error,
                    }
                    arr.push(value)
                });
                $.post(root + 'control/adIndex.html?cla=share&fun=checkUpload', {fileInfo:JSON.stringify(arr)}, function (res) {
                    $('.maskViewAnnex,.viewContentAnnex').removeClass('over');
                    if(res.warn === 2){
                        layer('share', 'uploadList', {'fileInfo': res.data, 'notClose': 1 })
                        //分片上传
                        for (var i = 0; i < res.data.length; i++) {
                            uploadChunks(fileList[i], res.data[i], url, htmlId)
                        }
                    }else{
                        msg(res.warn, 'error')
                    }
                }, 'json')
            }
            box.addEventListener(\"drop\",newHandle,false);
        });
            
    </script>";
    }

    /**
     * 删除图片
     */
    public function uploadImg(): bool|string
    {
        $file  = $_FILES['uploadImg'];
        $power = $this->get('power');
        $type  = $this->post('imgType');
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($type)) {
            $json['warn'] = '未找到上传的类型';
        } else {
            $result = $this->saveFile($file, $power, ['jpg', 'jpeg', 'png', 'gif']);
            if (!$result['code']) {
                $json['warn'] = $result['warn'];
            } else {
                $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' => $type, 'name' => $result['fileName'], 'format' => $result['suffix'], 'size' => $result['size'], 'src' => $result['src'], 'updateTime' => $this->time, 'time' => $this->time);
                $warn  = static::insert(array('table' => 'file', 'field' => $field));
                if ($warn == '新增成功') {
                    $json['warn']         = 2;
                    $json['data']['id']   = $field['id'];
                    $json['data']['src']  = root . $field['src'];
                    $root                 = root;
                    $json['data']['html'] = <<<efo
<li><input name='imgId[]' type='hidden' value='{$field['id']}' /><img class="li-ico" alt="" src="{$root}{$field['src']}"><a onclick="del_img('{$field['id']}','{$power}',this)" href='javascript:void(0)'><div><span class='u-icon-delete'><i></i></span></div></a></li>
efo;
                } else {
                    $json['warn'] = $warn;
                }
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 删除附件
     *
     * @return bool|string
     */
    public function delFile()
    {
        $power = $this->post('power');
        $file  = query("file", " id = '" . $this->post('id') . "' ");
        if (!$this->power($power, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } elseif (empty($file['id'])) {
            $json['warn'] = '没有找到此文件';
        } else {
            $warn = delete(array('table' => 'file', 'where' => " id = '$file[id]'"));
            if ($warn == '删除成功') {
                fileDelete($file['src']);
                $json['warn'] = 2;
            } else {
                $json['warn'] = "删除失败";
            }
        }
        return json_encode($json, 320);
    }


    /**
     * 文件列表展示
     *
     * @param string $id 对象ID
     * @param string $type 对象类型
     * @return string
     */
    public static function showFile(string $id, $type = ''): string
    {
        $where = '';
        if ($type) {
            $where .= " and target = '$type'";
        }
        $fileCollection = '';
        $result         = find(array('table' => " file", "where" => "targetId !='' and targetId = '$id' {$where} order by time asc"));
        foreach ($result['array'] as $array) {
            $size           = self::formatSize($array['size']);
            $title          = $array['name'];
            $fileCollection .= "
        <div class='file_block_bg'>
                <img src='" . root . "img/control/annex.svg'>
                <div class='file_block_right'>
                    <div class='file_block_right_text' title='$title'>$title</div>
                    <div><span class='title-color'>$size</span>" . self::view($array['src'], true, $array['name']) . "</div>
                </div>
        </div>
        ";
        }
        return $fileCollection ? "<div class='file_block_bg_parent'>" . $fileCollection . "</div>" : '';
    }

    /**
     * 图片列表展示
     *
     * @param string $id 对象ID
     * @param string $type 对象类型
     * @return string
     */
    public static function showImg($id, $type = ''): string
    {
        $root  = root;
        $where = '';
        if ($type) {
            $where .= " and target = '$type'";
        }
        $fileCollection = '';
        $result         = find(array('table' => " file", "where" => "targetId !='' and targetId = '$id' {$where} order by time asc"));
        foreach ($result['array'] as $array) {
            if (in_array($array['format'], ['jpg', 'jpeg', 'png', 'gif']))
                $fileCollection .= <<<efo
<li><a target="_blank" href="{$root}{$array['src']}"><img alt="" src="{$root}{$array['src']}"></a></li>
efo;
        }
        return $fileCollection ? "<div class='img-list'><ul class='img-ul'>" . $fileCollection . "</ul></div>" : '';
    }

    /**
     * 预览及下载
     *
     * @param string $src 文件地址
     * @param false $download 下载按钮
     * @param string $fileName 下载文件名称
     * @return string
     */
    public static function view(string $src, $download = false, $fileName = ''): string
    {
        $html = '';
        if (file_exists(serverRoot . $src)) {
            $suffix = self::getExtension($src);
            if (in_array($suffix, ['xlsx', 'pptx', 'ppt', 'xls', 'doc', 'docx'])) {
                $url  = self::wpsView(['name' => $fileName, 'href' => $src, 'format' => $suffix]);
                $html .= "\n<a target='_blank' href='" . $url . "' title='预览' class='del-row-button'>预览</a>";
            } elseif (in_array($suffix, ['jpg', 'png', 'jpeg', 'pdf', 'gif', 'bmp'])) {
                $url  = root . $src;
                $html .= "\n<a target='_blank' href='" . $url . "' title='预览' class='del-row-button'>预览</a>";
            }
            if ($download) {
                $url  = root . $src;
                $html .= "\n<a target='_blank' download='{$fileName}' href='" . $url . "' title='下载' class='del-row-button'>下载</a>";
            }
        }
        return $html;
    }

    /*
    wps文件预览
    $data = array(
        "format" => "文件格式，如doc,xls",
        "name" => "文件名称",
        "href" => "文件跟目录路径",
    );
    */
    public static function wpsView($data)
    {
        $format = '';
        if (isset($data['path'])) {
            $data['href'] = $data['path'];
        }
        if (isset($data['suffix'])) {
            $data['format'] = $data['suffix'];
        }
        //参数准备
        $wpsAppKey = '40bbc55d144c46e1996d0c7a1c5a5a46';
        $para      = array(
            "_w_appid"    => '1f3e2c82c20348b390460f6235f164d2',
            "_w_userid"   => self::$stid,
            "_w_fileId"   => md5(root . $data['href']),
            "_w_name"     => $data['name'],
            "_w_filepath" => root . $data['href'],
        );
        //判断文件类型
        $formatArray = array(
            "w" => array("doc", "docx"),
            "s" => array("xls", "xlsx"),
            "p" => array("ppt", "pptx"),
            "f" => array("pdf"),
        );
        foreach ($formatArray as $key => $value) {
            if (in_array($data['format'], $value)) {
                $format = $key;
            }
        }
        //按照键名对数组升序排序
        ksort($para);
        //生成签名字符串
        $get = $str = "";
        foreach ($para as $key => $value) {
            $str .= $key . "=" . $value;
            $get .= $key . "=" . $value . "&";
        }
        $str .= "_w_secretkey=" . $wpsAppKey;
        //签名
        $sign = hash_hmac('sha1', $str, $wpsAppKey, true);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        $get  .= "_w_signature=" . $sign;
        //生成URL
        return "https://wwo.wps.cn/office/" . $format . "/" . $para['_w_fileId'] . "?" . $get;
        //返回
    }
}
